package com.example.forum.utils;

import com.alibaba.fastjson.JSONObject;
import com.example.forum.domain.Message;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.util.*;

public class SimpleUtils {
    public static String generateUuid(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    public static String MD5(String key){
        if(StringUtils.isBlank(key)){   //key为空时
            return null;
        }
        //把key值用MD5加密
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }

    //将数据转换为json格式
    public static String toJson(int code, String msg, Map<String,Object> map){
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code",code);
        jsonObject.put("msg",msg);
        if(map!=null){
            for(String key:map.keySet()){
                jsonObject.put(key,map.get(key));
            }
        }
        return jsonObject.toJSONString();
    }
    public static String toJson(int code,String msg){
        return toJson(code,msg,null);
    }
    public static String toJson(int code){
        return toJson(code,null,null);
    }

    //截取TreeMap
    public static Map<String,List<Message>> subMap(Map<String, List<Message>> map, int start, int size){
        if(size>=map.size()){
            return map;
        }
        int index=0;
        int useSize=0;
        Map<String,List<Message>> newMap=new TreeMap<>();
        for(String key:map.keySet()){
            if (useSize>=size){
                break;
            }
            if(index>=start){
                newMap.put(key,map.get(key));
                start++;
                useSize++;
            }
            index++;
        }
        return newMap;
    }

    public static void main(String[] args) {
        Map<String,List<Message>> map=new TreeMap<>();
        map.put("0", new ArrayList<>());
        map.put("1", new ArrayList<>());
        map.put("2", new ArrayList<>());
        map.put("3", new ArrayList<>());
        Map<String, List<Message>> map1 = subMap(map, 1, 2);
        System.out.println(map1);
    }
}
